import {
  collectArticleAPI,
  discollectArticleAPI,
  dislikeArticleAPI,
  getArticleDetailByIdAPI,
  getArticlesByIdAPI,
  likeArticleAPI,
} from '@/api/article';
import { AppDispatch } from '..';
import { ActionType, ArticleDetailType } from '../reducer/article';
export const getArticlesByIdAction = (channel_id: number, timestamp = Date.now()) => {
  return async (dispatch: AppDispatch) => {
    const res = await getArticlesByIdAPI(channel_id, timestamp);
    console.log('res.data  ----->  ', res.data);
    dispatch({ type: 'article/saveList', payload: { ...res.data, channel_id } });
  };
};

export const updateArticlesByIdAction = (channel_id: number, timestamp = Date.now()) => {
  return async (dispatch: AppDispatch) => {
    const res = await getArticlesByIdAPI(channel_id, timestamp);
    dispatch({ type: 'article/updateListById', payload: { ...res.data, channel_id } });
  };
};

export const getArticleDetailByIdAction = (article_id: string) => {
  return async (dispatch: AppDispatch) => {
    const res = await getArticleDetailByIdAPI(article_id);
    dispatch({ type: 'article/saveDetail', payload: res.data });
  };
};

export const clearArticleDetailAction = (): ActionType => {
  return {
    type: 'article/saveDetail',
    payload: {} as ArticleDetailType,
  };
};

export const likeArticleAction = (target: string, isLiking: boolean) => {
  return async () => {
    if (isLiking) {
      await dislikeArticleAPI(target);
      return;
    }
    await likeArticleAPI({ target });
  };
};

export const collectArticleAction = (target: string, isCollect: boolean) => {
  return async () => {
    if (isCollect) {
      await discollectArticleAPI(target);
      return;
    }
    await collectArticleAPI(target);
  };
};
